﻿Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Media.Imaging
Imports System.Windows.Shapes
Imports WinInterop = System.Windows.Interop
Imports System.Runtime.InteropServices
Imports System.Windows.Threading
Imports System.Windows.Media.Animation


Partial Public Class ViewMainWindow
    Inherits CustomWindow.PT_CustomWindow

    Private Timer As DispatcherTimer
    Private AsyncCompleted As Boolean = False
    Private Bworker As ComponentModel.BackgroundWorker

    Sub New()
        _instance = Me
        ' Cet appel est requis par le concepteur.
        InitializeComponent()

        ' Ajoutez une initialisation quelconque après l'appel InitializeComponent().

    End Sub

    Friend Sub New(ByVal vm As MainWindowViewModel)
        _instance = Me

        ' Cet appel est requis par le concepteur.
        InitializeComponent()


        'Hide()

        'Dim strt As New StartWindow()

        'strt.ShowDialog()
        ' Ajoutez une initialisation quelconque après l'appel InitializeComponent().
        DataContext = vm

        Bworker = New ComponentModel.BackgroundWorker()

        AddHandler Bworker.DoWork, AddressOf BworkerDoWork
        AddHandler Bworker.RunWorkerCompleted, AddressOf BworkerRunWorkerCompleted

        Timer = New DispatcherTimer(DispatcherPriority.Background, Dispatcher)

        AddHandler Timer.Tick, AddressOf TimerTick
        Timer.Interval = TimeSpan.FromSeconds(1)
        Timer.Start()

        Bworker.RunWorkerAsync()
    End Sub

    Private Shared _instance As ViewMainWindow
    Public Shared ReadOnly Property Instance As ViewMainWindow
        Get
            Return _instance
        End Get
    End Property

    Protected Overrides Function GetWindowButtonsPlaceholder() As System.Windows.Controls.Decorator
        Return WindowButtonsPlaceholder
    End Function

    Private Sub GridTitle_MouseLeftButtonDown(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles GridTitle.MouseLeftButtonDown
        DragMove()
    End Sub

    Private Sub Thumb_DragDelta(ByVal sender As Object, _
                                ByVal e As System.Windows.Controls.Primitives.DragDeltaEventArgs)
        With Me
            If Not .WindowState = WindowState.Maximized Then
                If (.Width + e.HorizontalChange > GridPrincipale.ColumnDefinitions.Item(0).ActualWidth +
                    _GridPrincipale.ColumnDefinitions.Item(1).ActualWidth) Then .Width = .Width + e.HorizontalChange
                If (.Height + e.VerticalChange > MenuOMANE.ActualHeight + GridTitle.ActualHeight + 5) Then .Height = .Height + e.VerticalChange
            End If
        End With
    End Sub

    Private Sub ViewMainWindow_MouseLeftButtonUp(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles Me.MouseLeftButtonUp
        Try
            Dim t As String = Keyboard.FocusedElement.GetType().FullName
            Common.UI.Theme.NumericTextbox.DoTheRightThing(Keyboard.FocusedElement)
            Focus()
        Catch ex As Exception

        End Try
    End Sub

    Private Sub ViewMainWindow_StateChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.StateChanged
        If Me.WindowState = Windows.WindowState.Maximized Then
            Thumb_DragSize.Visibility = Windows.Visibility.Hidden
        Else
            Thumb_DragSize.Visibility = Windows.Visibility.Visible
        End If
    End Sub


    'Public Sub TreeViewItem_DataContextChanged(ByVal sender As Object, ByVal e As System.Windows.DependencyPropertyChangedEventArgs)

    '    If e.OldValue IsNot Nothing Then
    '        If treeviewstate.ContainsKey(e.OldValue) Then
    '            If treeviewstate(e.OldValue) IsNot Nothing Then
    '                Dim oldit As TreeViewItem = treeviewstate(e.OldValue)
    '                Dim newit As TreeViewItem = sender
    '                newit.IsExpanded = oldit.IsExpanded
    '            End If
    '            treeviewstate(e.OldValue) = sender
    '        Else
    '            treeviewstate.Add(e.OldValue, sender)
    '        End If
    '    End If

    'End Sub


    Private Sub MenuListBox_SizeChanged(ByVal sender As Object, ByVal e As System.Windows.SizeChangedEventArgs) Handles MenuListBox.SizeChanged
        Dim pt1 As System.Windows.Point = MenuListBox.PointToScreen(New System.Windows.Point())
        Dim rect As New System.Windows.Rect(pt1, MenuListBox.RenderSize)


        For Each elt In MenuListBox.Items
            Dim lstitem As ListBoxItem = MenuListBox.ItemContainerGenerator.ContainerFromItem(elt)
            Dim lstitem2 As ListBoxItem = PreviewMenuListBox.ItemContainerGenerator.ContainerFromItem(elt)

            Try
                Dim pt2 As System.Windows.Point = lstitem.PointToScreen(New System.Windows.Point())
                Dim rect2 As New System.Windows.Rect(pt2, lstitem.RenderSize)


                If rect.Contains(rect2) Then
                    'lstitem.Visibility = Visibility.Visible
                    lstitem2.Visibility = Visibility.Collapsed
                Else
                    'lstitem.Visibility = Visibility.Collapsed
                    lstitem2.Visibility = Visibility.Visible
                End If
            Catch ex As Exception

            End Try
        Next


    End Sub

    Private Sub TreeviewExpandAllButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        For Each elt In MenuTreeView.Items
            Dim c As TreeViewItem = MenuTreeView.ItemContainerGenerator.ContainerFromItem(elt)
            c.IsExpanded = True
            ExpandChildren(c)
        Next
    End Sub

    Private Sub ExpandChildren(ByVal parent As TreeViewItem)
        If parent.ItemContainerGenerator.Status = Primitives.GeneratorStatus.ContainersGenerated Then
            For Each e In parent.Items
                Dim c As TreeViewItem = parent.ItemContainerGenerator.ContainerFromItem(e)
                c.IsExpanded = True
                ExpandChildren(c)
            Next
        End If
    End Sub

    Private Sub CloseChildren(ByVal parent As TreeViewItem)
        If parent.ItemContainerGenerator.Status = Primitives.GeneratorStatus.ContainersGenerated Then
            For Each e In parent.Items
                Dim c As TreeViewItem = parent.ItemContainerGenerator.ContainerFromItem(e)
                c.IsExpanded = True
                CloseChildren(c)
            Next
        End If
    End Sub

    Private Sub TreeviewCloseAllButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        For Each elt In MenuTreeView.Items
            Dim c As TreeViewItem = MenuTreeView.ItemContainerGenerator.ContainerFromItem(elt)
            c.IsExpanded = False
            CloseChildren(c)
        Next
    End Sub


    'Private treeviewstate As New Hashtable
    'Private Sub MenuTreeView_DataContextChanged(ByVal sender As Object, ByVal e As System.Windows.DependencyPropertyChangedEventArgs) Handles MenuTreeView.DataContextChanged
    '    If e.NewValue IsNot Nothing And e.OldValue Is Nothing Then
    '        treeviewstate.Clear()
    '        For Each elt In MenuTreeView.Items
    '    End If
    'End Sub

    Private Sub TimerTick(ByVal sender As Object, ByVal e As EventArgs)
        If AsyncCompleted Then
            Timer.Stop()
            RemoveHandler Timer.Tick, AddressOf TimerTick
            RemoveHandler Bworker.DoWork, AddressOf BworkerDoWork
            RemoveHandler Bworker.RunWorkerCompleted, AddressOf BworkerRunWorkerCompleted

            DataContext = New MainWindowViewModel()
            Dim fading As Storyboard = Resources("FadingAnimation")
            fading.Begin()

            If WpfApp.Current IsNot Nothing Then
                AddHandler WpfApp.Current.Exit, AddressOf App.WpfAppCurrentExit
            End If
        End If
    End Sub

    Private Sub BworkerDoWork(ByVal sender As Object, ByVal e As ComponentModel.DoWorkEventArgs)
        Dim temp = App.Instance
    End Sub

    Private Sub BworkerRunWorkerCompleted(ByVal sender As Object, ByVal e As ComponentModel.RunWorkerCompletedEventArgs)
        AsyncCompleted = True
        Bworker.Dispose()
    End Sub

    Private previousgridlenght As GridLength
    Private previousminwdth As Double
    Private Sub BtnMaximizer_Checked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles BtnMaximizer.Checked
        MenuOMANE.Visibility = Windows.Visibility.Collapsed
        previousgridlenght = TreeViewColumn.Width
        previousminwdth = TreeViewColumn.MinWidth
        TreeViewColumn.Width = New GridLength(0)
        TreeViewColumn.MinWidth = 0

    End Sub

    Private Sub BtnMaximizer_Unchecked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles BtnMaximizer.Unchecked
        MenuOMANE.Visibility = Windows.Visibility.Visible
        TreeViewColumn.Width = previousgridlenght
        TreeViewColumn.MinWidth = previousminwdth

    End Sub
End Class

Public Class MaxHeightCalculator
    Implements IValueConverter

    Public Property Factor As Double
    Public Property Constant As Double
    Public Fallback As Double


    Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
        Return Math.Max(0, value - 1) * Factor + Constant
    End Function

    Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Throw New NotImplementedException()

    End Function
End Class